package service

import (
	"encoding/json"
	"fmt"
	"gitee.com/crack007/go_log"
	"github.com/crack007/fpm_metrics/src/config"
	"github.com/crack007/fpm_metrics/src/model"
	"io"
	"net/http"
	"time"
)

type FpmService struct {
}

// Stat 定时统计服务
func (s *FpmService) Stat() *model.FpmStatusModel {
	//  实现fpm状态抓取
	fpmStatusModel := model.NewFpmStatusModel()
	fpmUrl := config.GetFpmUrl()
	if fpmUrl == "" {
		return fpmStatusModel
	}
	client := http.Client{Timeout: 2 * time.Second}
	response, err := client.Get(fmt.Sprintf("%s?json", fpmUrl))
	defer func() {
		if response != nil {
			response.Body.Close()
		}
	}()
	if err != nil {
		go_log.Error(err)
		return fpmStatusModel
	}
	bytes, err := io.ReadAll(response.Body)
	if err != nil {
		go_log.Error(err)
		return fpmStatusModel
	}
	err = json.Unmarshal(bytes, fpmStatusModel)
	if err != nil {
		go_log.Error(err)
		return fpmStatusModel
	}
	return fpmStatusModel
}
